package com.zry.pda.ui.activity

import android.app.AlertDialog
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.Log
import android.view.View
import com.zry.pda.R
import com.zry.pda.been.*
import com.zry.pda.databinding.ActivitySectionNumberStorageBinding
import com.zry.pda.greendao.entity.OutTreasuryCode
import com.zry.pda.greendao.entity.PackingOperationInfo
import com.zry.pda.presenter.HttpServer
import com.zry.pda.presenter.SectionNumberStoragePresenter
import com.zry.pda.retrofit.ShowUserView
import com.zry.pda.ui.base.BaseActivity
import com.zry.pda.utils.InputCodeFilter
import com.zry.pda.utils.StringListUtil
import com.zry.pda.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_section_number_storage.*
import kotlinx.android.synthetic.main.common_title.*

class SectionNumberStorageActivity : BaseActivity(), ShowUserView {

    private var sectionNumberStorageBinding: ActivitySectionNumberStorageBinding? = null
    private var sectionNumberStoragePresenter: SectionNumberStoragePresenter? = null

    var longAndShortCodeList: ArrayList<LongAndShortCode>? = null
    var title = ""

    var storeOrderBean: StoreOrderBean? = null
    var packingOperationInfo: PackingOperationInfo? = null
    var outStock: OutStock? = null
    var outTreasuryCode: OutTreasuryCode? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_section_number_storage
    }

    override fun initData() {
        title = intent.getStringExtra("title")
        submitConfirmSectionNumber.text = title
        when (title) {
            "批量入库", "号段入库" -> {
                storeOrderBean = intent.getSerializableExtra("storeOrderBean") as StoreOrderBean
            }
            "批量装箱", "号段装箱" -> {
                packingOperationInfo = intent.getSerializableExtra("packingOperationInfo") as PackingOperationInfo
            }
            "批量出库", "号段出库", "虚拟托盘" -> {
                outStock = intent.getSerializableExtra("outStock") as OutStock
                outTreasuryCode = intent.getSerializableExtra("outTreasuryCode") as OutTreasuryCode

                endCodeRelative.visibility = View.GONE
                sinceStartTV.visibility = View.GONE
            }
        }

        titleCenterText.text = title
        commonLeftLinearLayout.setOnClickListener { finish() }

        sectionNumberStorageBinding = viewDataBinding as ActivitySectionNumberStorageBinding
        sectionNumberStoragePresenter = SectionNumberStoragePresenter(this)
        sectionNumberStorageBinding?.handlerClick = sectionNumberStoragePresenter

        longAndShortCodeList = arrayListOf()
        longAndShortCodeList!!.add(LongAndShortCode("1", "1"))
        longAndShortCodeList!!.add(LongAndShortCode("1", "1"))
        initView()
    }

    private fun initView() {
        sectionCodeET.filters = arrayOf<InputFilter>(InputCodeFilter())
        sectionCodeET.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
            override fun afterTextChanged(editable: Editable?) {
                val sectionCode = sectionCodeET.text.toString().trim()
                Log.e("codeString", sectionCode)
                if (!sectionCode.isEmpty()) {
                    setLongCode(sectionCode)
                    sectionCodeET.setText("")
                } else {
                    getEditFocusTrue()
                }
            }
        })
    }


    fun setLongCode(codeString: String) {
        when (title) {
            "批量入库", "号段入库" -> {
                when (storeOrderBean?.StoreType) {
                    "1" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, storeOrderBean!!.ProductID, "2", "", this)
                    }
                    "2", "3" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(
                            codeString, storeOrderBean!!.ProductID, "2",
                            storeOrderBean!!.StoreType, "", this
                        )
                    }
                }
            }

            "批量装箱", "号段装箱" -> {
                when (packingOperationInfo?.packLevelID) {
                    "2" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, packingOperationInfo!!.productID, "1", "", this)
                    }
                    "3" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(
                            codeString, packingOperationInfo!!.productID, "1", "",
                            "", this
                        )
                    }
                }
            }
            "批量出库", "号段出库" -> {
                when (outTreasuryCode?.outLevelID) {
                    "1" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, outTreasuryCode!!.productID, "3", "", this)
                    }
                    "2", "3" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(
                            codeString, outTreasuryCode!!.productID, "3", "", "",
                            this
                        )
                    }
                }
            }
            "虚拟托盘" -> {
                //追溯码
                HttpServer(this).getLongTraceCode(codeString, outTreasuryCode!!.productID, "9", "", this)
            }
        }
    }


    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            5 -> {
                val resultData = data as ResultCode
                if (resultData.state == "1") {
                    val longAndShortCode = LongAndShortCode(resultData.CodeID, resultData.shortCode)
                    if (title == "虚拟托盘") {

                        if (sectionNumberStartCode.text.isEmpty()) {

                            sectionNumberStartCode.text = longAndShortCode.longCode
                            sectionNumberTV.text = resultData.OutQuality
                        } else {
                            AlertDialog.Builder(this)
                                .setTitle("替换追溯码")
                                .setMessage("您是否放弃此托盘出库？")
                                .setPositiveButton("放弃") { dialog, which ->


                                    sectionNumberStartCode.text = longAndShortCode.longCode
                                    sectionNumberTV.text = resultData.OutQuality

                                    dialog.dismiss()
                                }.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                                .setCancelable(false)?.create()?.show()
                        }

                    } else {
                        setCodeNumber(longAndShortCode)
                    }
                } else {
                    toast(resultData.Message)
                }
            }
            6 -> {
                val resultData = data as ResultFlowCode
                if (resultData.state == "1") {
                    val longAndShortCode = LongAndShortCode(resultData.Code, resultData.shortCode)
                    setCodeNumber(longAndShortCode)
                } else {
                    toast(resultData.Message)
                }
            }
        }
    }

    private fun setCodeNumber(longAndShortCode: LongAndShortCode) {
        if (sectionNumberStartCode.text.toString().isEmpty()) {
            sectionNumberStartCode.text = longAndShortCode.longCode
            longAndShortCodeList!![0] = longAndShortCode
        } else if (!sectionNumberStartCode.text.toString().isEmpty() && sectionNumberEndCode.text.toString().isEmpty()) {
            sectionNumberEndCode.text = longAndShortCode.longCode
            longAndShortCodeList!![1] = longAndShortCode
        } else if (sectionNumberStartCode.text.toString().isEmpty() && !sectionNumberEndCode.text.toString().isEmpty()) {
            sectionNumberStartCode.text = longAndShortCode.longCode
            longAndShortCodeList!![0] = longAndShortCode
        } else {
            return ToastUtil.toast(this, "初始和结束号码已经填写完整")
        }

        if (!sectionNumberStartCode.text.toString().isEmpty() && !sectionNumberEndCode.text.toString().isEmpty()) {
            sectionNumberTV.text = ((StringListUtil().getStringIntercept(
                sectionNumberEndCode.text.toString(),
                6
            ).toInt() - StringListUtil().getStringIntercept(
                sectionNumberStartCode.text.toString(), 6
            ).toInt()) + 1).toString()
        }
    }

    fun getEditFocusTrue() {
        //获取焦点
        sectionCodeET.isFocusable = true
        sectionCodeET.isFocusableInTouchMode = true
        //显示光标
        sectionCodeET.requestFocus()
        sectionCodeET.isCursorVisible = true
    }
}
